package com.xx.springboot.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xx.springboot.entity.CommonResult;
import com.xx.springboot.mapper.UserMapper;
import com.xx.springboot.service.ILoginService;
import com.xx.springboot.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * Created by xiaoxiunique on 2018-9-14.
 */
@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private IUserService userService;


    /**
     * 自动登录接口
     *
     * @param jsonObject
     * @return
     */
    @Override
    public CommonResult autoLogin(JSONObject jsonObject) {
        String userName = jsonObject.getString("userName");
        String password = jsonObject.getString("password");

        Subject currentUser = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken();
        try {
            currentUser.login(token);
            return new CommonResult(CommonResult.STATUS_SUCCESS, "登录成功");
        }catch (Exception e){
            return new CommonResult(CommonResult.STATUS_ERROR, "自动登录失败");
        }
    }

    /**
     * 根据用户名和密码查询到对应的用户
     *
     * @param userName
     * @param password
     * @return
     */
    @Override
    public CommonResult getUser(String userName, String password) {

        return userService.loginUser(userName, password);
    }

    /**
     * 获取到当前登录用户的权限
     *
     * @return
     */
    @Override
    public CommonResult getInfo() {
        // 从session 中获取用户信息
        Session session = SecurityUtils.getSubject().getSession();
        JSONObject userInfo = (JSONObject) session.getAttribute("userInfo");
        String userName = userInfo.getString("userName");

        return null;
    }

    /**
     * 退出登录
     *
     * @return
     */
    @Override
    public CommonResult logout() {
        return null;
    }
}
